/** @odoo-module **/
import init_grid_options from '../ag_grid/gridOptions.js'
import {formatPrice, add_dish_bom_id, formatId, toObj, add_dish_key_id,keepTwoDecimal} from "../ag_grid/tool.js";
import selectCellEditor from "../ag_grid/selectCellEditor.js";
import numberCellEditor from "../ag_grid/numberCellEditor.js";
import unitCellEditor from "../ag_grid/unitCellEditor.js";
import selectMaterialCellEditor from "../ag_grid/selectMaterialCellEditor.js";
import selectMaterialByNetCellEditor from "../ag_grid/selectMaterialByNetCellEditor.js";

class actionCellRenderer {
    init(params) {
        if(params.node.data.bom.length == 0){
            let el = document.createElement('div');
            this.eGui = el;
            return;
        }
        let data = params.data;

        this.owl = params.context.owl_widget;
        let el = document.createElement('div');
        el.setAttribute('class','d-flex align-items-center');
        el.setAttribute('style','height: 100%;');

        let _html = '';
        _html += `<button type="button" class="btn btn-outline-primary btn-xs">复制</button>`;
        el.innerHTML = _html;
        this.eGui = el;

        let btnEl = el.getElementsByClassName('btn')[0];
        const fn = (ev)=>{
            ev.stopPropagation();
            this.owl.handleAction(data);
        };
        btnEl.onclick = _.debounce(fn,300);
    }
    getGui() {
        return this.eGui;
    }
    refresh(params) {
        return false;
    }
    destroy() {

    }
}

const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    EventBus,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent,
    onWillUnmount,
    onWillDestroy
} = owl;

function useBus(bus, eventName, callback) {
    const component = useComponent();
    useEffect(
        () => {
            const listener = callback.bind(component);
            bus.addEventListener(eventName, listener);
            return () => bus.removeEventListener(eventName, listener);
        },
        () => []
    );
}
// 菜品基础信息表单
class CreatDishForm extends Component {
    static template = xml`
    <div class="mt-3 row">
                            <label class="col-sm-2 col-form-label text-right">
                                <span class="text-danger" style="margin-right: 4px;">*</span>
                                菜品名称
                            </label>
                            <div class="col-sm-5">
                                <input type="text" placeholder="请输入菜品名称" class="form-control" t-model="state.creatDishForm.name"
                                       t-on-change="inputOnChange"/>
                            </div>
                            <div class="col-sm-5 col-form-label" t-if="state.creatDishForm.name!=state.old_dish_key_name and props.is_edit">
                                <span class="text-grey" style="margin-right: 4px;">原名：</span><t t-esc="state.old_dish_key_name"/>
                            </div>
                        </div>
                        <div class="mt-3 row" t-if="props.is_edit">
                            <label class="col-sm-2 col-form-label text-right">成本</label>
                            <div class="col-sm-5">
                                <input type="number" placeholder="请输入菜品费用" class="form-control"
                                       t-model="state.creatDishForm.dish_cost" min="0" t-on-change="inputOnChange" disabled="true"/>
                            </div>
                            <div class="col-sm-5 col-form-label">
                                <span class="text-grey">根据配比更新</span>
                            </div>
                        </div>
                        <div class="mt-3 row">
                            <label class="col-sm-2 col-form-label text-right">售价</label>
                            <div class="col-sm-5">
                                <input type="number" placeholder="请输入菜品售价" class="form-control"
                                       t-model="state.creatDishForm.price" min="0" t-on-change="inputOnChange"/>
                            </div>
                        </div>
                        <div class="mt-3 row">
                            <label class="col-sm-2 col-form-label text-right">种类</label>
                            <div class="col-sm-10">
                                <div class="col-form-label">
                                    <t t-esc="state.dish_top_category_name"/>
                                </div>
                            </div>
                        </div>
        
                        <div class="mt-3 row">
                            <label class="col-sm-2 col-form-label text-right">
                                <span class="text-danger" style="margin-right: 4px;">*</span>
                                烧法
                            </label>
                            <div class="col-sm-4">
                                <select class="form-select" t-model="state.creatDishForm.cooking_method_id"
                                        t-on-change="inputOnChange">
                                    <option value="0" name="cooking_method_id">请选择</option>
                                    <t t-foreach="cooking_category" t-as="v" t-key="v_index">
                                        <option t-att-value="v.id" name="cooking_method_id">
                                            <t t-esc="v.name_cn || v.name"/>
                                        </option>
                                    </t>
                                </select>
                            </div>
                        </div>
                        <div class="mt-3 row">
                            <label class="col-sm-2 col-form-label text-right">其他</label>
                            <div class="col-sm-10">
                                <div class="col-form-label">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="checkbox" t-model="state.creatDishForm.easy_meal"
                                               name="easy_meal"/>
                                        <label class="form-check-label">下饭</label>
                                    </div>
                                </div>
                            </div>
                        </div>
        <!--<div class="d-flex mt-3">-->
            <!--<div class="text-danger" style="flex:1">-->
               <!--<t t-esc="state.msg"/>-->
            <!--</div>-->
        <!--</div>-->
    `;

    setup() {
        this.cooking_category = [];
        this.state = useState({
            creatDishForm: {},
            msg: '',
            dish_top_category_name: '',
            old_dish_key_name: '',
            // isDestroy:false
        });
        onMounted(() => {
            this.cooking_category = this.env.getIndex().cooking_category;
            let creatDishForm = JSON.parse(JSON.stringify(this.props.data));
            this.state.old_dish_key_name = creatDishForm.name || '';
            let easy_meal = creatDishForm.easy_meal == 'N' ? false : !creatDishForm.easy_meal ? false : true;
            this.state.creatDishForm = {
                ...creatDishForm,
                easy_meal:easy_meal
            };
            let dish_top_category = this.env.getIndex().dish_top_category.find(v => v.id == creatDishForm.dish_top_category_id);
            this.state.dish_top_category_name = dish_top_category.name;
        });
        onWillUpdateProps(nextProps => {

        });
        // onWillUnmount(()=>{
        //
        // })
        // onWillDestroy(()=>{
        //     this.state.isDestroy = true;
        // })
        useBus(this.env.bus, 'checkForm', ({detail}) => {
            this.checkForm();
            detail.msg += this.state.msg;
        });
        useBus(this.env.bus, 'getForm', ({detail}) => {
            let name = this.state.creatDishForm.name.replace(/\s+/g, "");
            let creatDishForm = this.state.creatDishForm;
            detail.name = name;
            detail.dish_top_category_id = creatDishForm.dish_top_category_id;
            detail.cooking_method_id = Number(this.state.creatDishForm.cooking_method_id) || 0;
            detail.dish_cost = Number(creatDishForm.dish_cost||0);
            detail.price = Number(creatDishForm.price||0);
            detail.easy_meal = this.state.creatDishForm.easy_meal ? 'Y' : 'N';
        });

        // this.env.bus.addEventListener('checkForm', ({detail}) => {
        //     if(this.state.isDestroy){
        //         return;
        //     }
        //     this.checkForm();
        //     detail.msg += this.state.msg;
        // });
        // this.env.bus.addEventListener('getForm', ({detail}) => {
        //     if(this.state.isDestroy){
        //         return;
        //     }
        //     let name = this.state.creatDishForm.name.replace(/\s+/g, "");
        //     let creatDishForm = this.state.creatDishForm;
        //     detail.name = name;
        //     detail.dish_top_category_id = creatDishForm.dish_top_category_id;
        //     detail.cooking_method_id = Number(this.state.creatDishForm.cooking_method_id) || 0;
        //     detail.dish_cost = Number(creatDishForm.dish_cost||0);
        //     detail.price = Number(creatDishForm.price||0);
        //     detail.easy_meal = this.state.creatDishForm.easy_meal ? 'Y' : 'N';
        // });
    }
    static props = {
        is_edit: {type: Boolean, optional: true},
        data:{type: Object, optional: true}
    };


    inputOnChange(e) {
        this.checkForm();
        this.env.setMsg(this.state.msg);
    }

    checkForm() {
        // console.log('checkForm');
        // console.log(this.state.creatDishForm);
        let name = this.state.creatDishForm.name.replace(/\s+/g, "");
        let dish_top_category_id = this.state.creatDishForm.dish_top_category_id;
        this.state.creatDishForm.name = name;
        if (name == '') {
            this.state.msg = '请填写菜品名称；';
            return;
        }
        // console.log(this.env.getDishKeyId(name, Number(dish_top_category_id)));
        if (!this.props.is_edit && this.env.getDishKeyId(name, Number(dish_top_category_id))) {
            this.state.msg = '该菜品已存在；';
            return;
        }
        if (this.props.is_edit && name != this.state.old_dish_key_name && this.env.getDishKeyId(name, Number(dish_top_category_id))) {
            this.state.msg = '该菜品已存在；';
            return;
        }
        if (this.state.creatDishForm.dish_cost != '' && !(/^-?\d+\.?\d{0,2}$/.test(this.state.creatDishForm.dish_cost))) {
            this.state.msg = '费用小数点后最多两位；';
            return;
        }
        if (this.state.creatDishForm.price != '' && !(/^-?\d+\.?\d{0,2}$/.test(this.state.creatDishForm.price))) {
            this.state.msg = '售价小数点后最多两位；';
            return;
        }

        if (Number(this.state.creatDishForm.cooking_method_id) === 0) {
            this.state.msg = '请选择烧法；';
            return;
        }
        this.state.msg = '';
    }
}
// 菜品BOM
class CreatDishBom extends Component {
    static template = xml`
        <div t-ref="dishWholeGrid" style="width: 100%;height:300px" class="ag-theme-balham myGrid mt-3"/>
        <!--<div class="row mt-3 mb-3">-->
            <!--<div class="col-auto">-->
                <!--<button type="button" class="btn btn-outline-primary btn-xs" t-on-click.stop="handleAddRow">添加</button>-->
            <!--</div>-->
        <!--</div>-->
        <!--<div class="d-flex mt-3">-->
            <!--<div class="text-danger" style="flex:1">-->
               <!--<t t-esc="state.msg"/>-->
            <!--</div>-->
        <!--</div>-->
    `;
    setup() {
        this.dishWholeGrid_ref = useRef('dishWholeGrid');
        this.pinnedBottomRowData = [{
            id: 'bottom',
        }];
        this.state = useState({
            isGbom:false,
            msg:'',
        });
        onMounted(() => {
            let _this = this;
            this.state.isGbom = this.env.getIsGbom();
            this.gridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                suppressRowClickSelection: false,
                columnDefs: [],
                valueCache: 1,
                context: {
                    owl_widget: _this
                },
                getContextMenuItems: (e) => {
                    return _this.setAGMenus(e);
                },
                onGridReady: function (params) {
                    let defaultSortModel = [
                        {colId: 'material_sequence_no', sort: 'asc', sortIndex: 0},
                    ];
                    params.columnApi.applyColumnState({state: defaultSortModel});
                },
                onCellValueChanged: (e) => {
                    // console.log(e);
                    _this.onCellValueChanged(e);
                },
                processDataFromClipboard: () => {
                    return []
                },
                pinnedBottomRowData: _this.pinnedBottomRowData,
                columnTypes: {
                    editableColumn: {
                        editable: (params) => {
                            return _this.isCellEditable(params);
                        },
                    }
                },
                getRowStyle: params => {
                    if (params && params.node && params.node.data && params.node.data.id == 'bottom') {
                        return { background: '#f4f6fa' };
                    }
                },
                // stopEditingWhenCellsLoseFocus:true
            });

            this.dishWholeGrid = new agGrid.Grid(this.dishWholeGrid_ref.el, this.gridOptions);
            this.setColumnDefs();
            this.setRowData(this.props.data.dish_bom||[]);
            this.dish_key_id = this.props.data.dish_key_id;
        });
        onWillUpdateProps(nextProps => {

        });
        useBus(this.env.bus, 'checkWhole', ({detail}) => {
            this.checkWhole();
            detail.msg += this.state.msg;
        });
        useBus(this.env.bus, 'getWhole', ({detail}) => {
            detail.list = this.getSaveData();
        });
        useBus(this.env.bus, 'copyDishBom', ({detail}) => {
            if(detail.type == 'add'){
                this.addRows(detail.bom);
            }
            if(detail.type == 'copy'){
                this.setRowData(detail.bom,1);
            }
        });

        // this.env.bus.addEventListener('checkWhole', ({detail}) => {
        //     if(this.state.isDestroy){
        //         return;
        //     }
        //     this.checkWhole();
        //     detail.msg += this.state.msg;
        // });
        // this.env.bus.addEventListener('getWhole', ({detail}) => {
        //     if(this.state.isDestroy){
        //         return;
        //     }
        //     detail.list = this.getSaveData();
        // });


        // this.handleAddRow = _.debounce(this.addRow, 300);
    }
    static props = {
        is_edit: {type: Boolean, optional: true},
        data:{type: Object, optional: true}
    };

    addRows(data){
        let rowData = JSON.parse(JSON.stringify(data));
        rowData.forEach(v=>{
            v.id = add_dish_bom_id();
        });
        this.gridOptions.api.applyTransactionAsync({add: rowData}, (res) => {
            // this.gridOptions.api.redrawRows();
        });
    }

    checkWhole() {
        this.gridOptions.api.stopEditing();
        let rowData = this.getRowData();
        let flag = true;
        rowData.forEach(v => {
            if (!v.material_id) {
                return;
                // this.state.msg = '配比：请选择食材(毛料)';
                // flag = false
            }
            if (!v.expansion) {
                this.state.msg = '配比：请填写出材率；';
                flag = false
            }
            if (this.state.isGbom) {
                if (!v.gbom_qty_mid && !v.gbom_qty_high) {
                    this.state.msg = '配比：请填写套餐毛料或称重毛料；';
                    flag = false
                }
            } else {
                if (!v.bom_qty_mid && !v.bom_qty_high) {
                    this.state.msg = '配比：请填写套餐净料或称重净料；';
                    flag = false
                }
            }
            if (!v.unit_id) {
                this.state.msg = '配比：请选择单位；';
                flag = false
            }
            if (!v.process_id) {
                this.state.msg = '配比：请选择工序；';
                flag = false
            }
            if (!this.state.isGbom) {
                if (!v.material_id_net_material_id) {
                    this.state.msg = '配比：请选择食材(净料)；';
                    flag = false
                }
            }
        });
        if (flag) {
            this.state.msg = ''
        }
        return flag
    }

    get material_item_net_material(){
        let arr = [];
        this.env.getIndex().material_item.forEach(v => {
            arr.push({
                id: v.id + '_' + v.net_material_id,
                name: this.env.getGlobal().net_material[v.net_material_id].name,
                material_name: v.name,
                material_id: v.id,
                net_material_id: v.net_material_id
            })
        });
        return arr;
    }
    get material_item_net_material_obj(){
        return toObj(this.material_item_net_material, 'id');
    }

    setColumnDefs() {
        let isGbom = this.state.isGbom;
        let cols = [
            {
                headerName: '食材(净料)',
                field: 'material_id_net_material_id',
                menuTabs: [],
                flex: 1,
                cellEditor: selectMaterialByNetCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.material_item_net_material
                    };
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.material_item_net_material_obj[params.value].name;
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
                hide: isGbom
            },
            {
                headerName: '食材(毛料)',
                field: 'material_id',
                menuTabs: [],
                flex: 1,
                cellEditor: selectMaterialCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.env.getIndex().material_item
                    };
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().material_item[params.value].name;
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
                cellClassRules: {
                    'bg_gray': (params) => !isGbom
                },
            },
            {
                field: 'net_material_id',
                hide: true
            },
            {
                headerName: '工序',
                field: 'process_id',
                menuTabs: [],
                width: 60,
                cellEditor: selectCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.env.getIndex().dish_process_category
                    };
                },
                cellRenderer: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().dish_process_category[params.value].name
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
            },
            {
                headerName: '套餐(毛料)',
                field: 'gbom_qty_high',
                menuTabs: [],
                width: 80,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                type: 'editableColumn',
                hide: !this.state.isGbom
            },
            {
                headerName: '称重(毛料)',
                field: 'gbom_qty_mid',
                menuTabs: [],
                width: 80,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                type: 'editableColumn',
                hide: !this.state.isGbom
            },
            {
                headerName: '套餐(净料)',
                field: 'bom_qty_high',
                menuTabs: [],
                width: 80,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                type: 'editableColumn',
                hide: this.state.isGbom
            },
            {
                headerName: '称重(净料)',
                field: 'bom_qty_mid',
                menuTabs: [],
                width: 80,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                type: 'editableColumn',
                hide: this.state.isGbom
            },
            {
                headerName: '单位',
                field: 'unit_id',//unit_id  diff_purchase_unit_id
                menuTabs: [],
                width: 60,
                cellEditor: unitCellEditor,
                // cellEditor: selectCellEditor,
                cellEditorParams: (params) => {
                    let material_id = params.data.material_id;
                    let values = [];
                    if (material_id) {
                        values = params.context.owl_widget.env.searchUnit(material_id);
                    }
                    return {
                        values: values,
                        material_id: material_id
                    };
                },
                cellRenderer: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().material_purchase_unit_category[params.value].name
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
            },
            {
                field: 'diff_main_unit_bom_unit_ratio',
                hide: true
            },
            {
                headerName: '出材率',
                field: 'expansion',
                menuTabs: [],
                width: 60,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                type: 'editableColumn',
            },
            {
                headerName: '元(套餐)',
                field: 'price',
                menuTabs: [],
                width: 60,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.calculatePrice(params.data);
                    return value;
                },
                valueFormatter: params => {
                    if ((params.data && params.data.material_id)||params.data.id == 'bottom') {
                        return params.value;
                    } else {
                        return ''
                    }
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                type: 'editableColumn',
            },
            {
                headerName: '元(称重)',
                field: 'priceByWeight',
                menuTabs: [],
                width: 60,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.calculateByWeightPrice(params.data);
                    return value;
                },
                valueFormatter: params => {
                    if ((params.data && params.data.material_id)||params.data.id == 'bottom') {
                        return params.value;
                    } else {
                        return ''
                    }
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                type: 'editableColumn',
            },
            {
                field: 'material_sequence_no',
                hide: true
            },

        ];
        this.gridOptions.api.setColumnDefs(cols);
    }

    setRowData(dish_bom,isCopy) {
        let data = JSON.parse(JSON.stringify(dish_bom));
        data.forEach((v, i) => {
            if (!v.material_sequence_no) {
                v.material_sequence_no = i + 1
            }
            if(isCopy){
                v.id = add_dish_bom_id();
            }
            v.material_sequence_no = v.material_sequence_no * 100;
            if (!v.net_material_id) {
                v.net_material_id = this.env.getGlobal().material_item[v.material_id].net_material_id;
            }
            v.material_id_net_material_id = v.material_id + '_' + v.net_material_id;
        });
        // console.log(dish_bom);
        let _l = data.length;
        if(_l < 15){
            let default_process_id = this.env.getGlobal().default_process_id;
            for (let i = _l;i<15;i++) {
                data.push({
                    id: add_dish_bom_id(),
                    expansion: '',
                    gbom_qty_high: '',
                    gbom_qty_mid: '',
                    bom_qty_high: '',
                    bom_qty_mid: '',
                    material_id: '',
                    process_id: '',//默认 ‘无’
                    unit_id: '',
                    net_material_id: '',
                    material_sequence_no:(i+1) * 100
                })
            }
        }
        // data.sort((a,b)=>{return a.material_sequence_no-b.material_sequence_no});//排序
        this.gridOptions.api.setRowData(data);
        this.gridOptions.api.redrawRows();
        this.checkWhole();
    }

    // 配比部分
    isCellEditable(params) {
        let flag = true;
        let data = params.data;
        let colId = params.colDef.field;
        if (data.id == 'bottom') {
            flag = false;
        }
        if (colId == 'material_id' && !this.state.isGbom) {
            flag = false;
        }
        return flag;
    }

    // 单元格改变
    onCellValueChanged(params) {
        // console.log('-----onCellValueChanged----');
        // console.log(params);
        if (params.source == "edit" && params.colDef.field == "material_id") {
            this.onMaterialChanged(params);
        }
        if (params.source == "edit" && params.colDef.field == "material_id_net_material_id") {
            let id = params.newValue;
            let net_material_id = this.material_item_net_material_obj[id].net_material_id;
            let material_id = this.material_item_net_material_obj[id].material_id;

            params.node.setDataValue('net_material_id', net_material_id);
            params.node.setDataValue('material_id', material_id);

            let unit_id = this.material_item[material_id].main_unit_id;
            if (unit_id != params.data.unit_id) {
                params.node.setDataValue('unit_id', unit_id);
            }
        }
        if (params.source == "edit" && params.colDef.field == "bom_qty_high") {
            // 一菜一料默认与套餐一致
            params.node.setDataValue('bom_qty_mid', params.newValue);
        }
        if (params.source == "edit" && params.colDef.field == "gbom_qty_high") {
            // 一菜一料默认与套餐一致
            params.node.setDataValue('gbom_qty_mid', params.newValue);
        }
        this.checkWhole();
        this.env.setMsg(this.state.msg);
    }

    onMaterialChanged(params) {
        // console.log('-----onMaterialChanged----');
        let data = params.node.data;
        let material_id = params.newValue;
        let unit_id = this.env.getGlobal().material_item[material_id].main_unit_id;
        if (unit_id != data.unit_id) {
            params.node.setDataValue('unit_id', unit_id);
        }
        let net_material_id = this.env.getGlobal().material_item[material_id].net_material_id;
        params.node.setDataValue('net_material_id', net_material_id);

        if(material_id){
            if(!data.expansion){
                params.node.setDataValue('expansion', 1);
            }
            if(!data.process_id){
                let default_process_id = this.env.getGlobal().default_process_id;
                params.node.setDataValue('process_id', default_process_id);
            }
        }
    }

    // 右键菜单
    setAGMenus(e) {
        // console.log('-------setAGMenus-------');
        // console.log(e);
        let node = e.node || {};
        // if (!node.data) {
        //     return;
        // }
        // if(!e.column){
        //     return;
        // }
        let _this = this;
        let menu = [
            {
                name: '新增一行',
                action: () => {
                    _this.addRow(node, 'down');
                }
            },
        ];
        if (node.data) {
            menu = [
                {
                    name: '向下新增一行',
                    action: () => {
                        _this.addRow(node, 'down');
                    },
                },
                {
                    name: '向上新增一行',
                    action: () => {
                        _this.addRow(node, 'up');
                    }
                },
                {
                    name: '删除本行',
                    action: () => {
                        _this.removeRow(node);
                    },
                    cssClasses: ['text-danger'],
                }
            ];
            if(node.data.material_id){
                menu.push({
                    name: '食材详情',
                    action: () => {
                        _this.env.openCreatMaterialModal({
                            id: node.data.material_id
                        },()=>{
                            _this.gridOptions.api.refreshCells({force: true});//刷新表格
                        });
                    },
                    cssClasses: ['text-success'],
                })
            }
        }
        return menu;
    }

    removeRow(node) {
        let data = node.data;
        this.gridOptions.api.applyTransactionAsync({remove: [data]}, (res) => {
            this.gridOptions.api.redrawRows();
        });
    }

    addRow(node, direction) {
        let default_process_id = this.env.getGlobal().default_process_id;
        let data = node.data || {material_sequence_no: 100};
        let newItem = {
            id: add_dish_bom_id(),
            expansion: '',
            gbom_qty_high: '',
            gbom_qty_mid: '',
            bom_qty_high: '',
            bom_qty_mid: '',
            material_id: '',
            process_id: '',//默认 ‘无’
            unit_id: '',
            net_material_id: ''
        };
        if (direction == 'up') {
            newItem.material_sequence_no = data.material_sequence_no - 1;
        }
        if (direction == 'down') {
            newItem.material_sequence_no = data.material_sequence_no + 1;
        }
        // console.log(newItem);
        this.gridOptions.api.applyTransactionAsync({add: [newItem]}, (res) => {
            this.gridOptions.api.redrawRows();
        });
    }

    calculatePrice(data) {
        let price = 0;
        if (data.id == 'bottom') {
            // 底部总价
            let rowData = this.getRowData();
            let result = [];
            rowData.forEach(v => {
                result.push(this.calculatePrice(v));
            });
            let sum = eval(result.join("+"));
            price = formatPrice(sum);
            // console.log(price);
        } else {
            let {gbom_qty_high,unit_id,material_id} = data;
            if(gbom_qty_high && unit_id && material_id){
                price = this.env.getMaterialPrice(material_id,unit_id,gbom_qty_high);
                price = price*0.01;
                price = formatPrice(price);
            }
            // price = this.env.getDishBomPrice(data);
        }
        return price;
    }

    calculateByWeightPrice(data) {
        let price = 0;
        if (data.id == 'bottom') {
            // 底部总价
            let rowData = this.getRowData();
            let result = [];
            rowData.forEach(v => {
                result.push(this.calculateByWeightPrice(v));
            });
            let sum = eval(result.join("+"));
            price = formatPrice(sum);
        } else {
            let {gbom_qty_mid,unit_id,material_id} = data;
            if(gbom_qty_mid && unit_id && material_id){
                price = this.env.getMaterialPrice(material_id,unit_id,gbom_qty_mid);
                price = price*0.01;
                price = formatPrice(price);
            }
            // price = this.env.getDishBomByWeighPrice(data);
        }
        return price;
    }
    getSaveData() {
        let _this = this;
        let data = [];
        let rowData = this.getRowData();
        let dish_key_id = formatId(this.dish_key_id);
        rowData.sort((a, b) => a.material_sequence_no - b.material_sequence_no);
        rowData.forEach((v,i)=>{
            if(!v.material_id){
                return;
            }
            let item = {
                id: formatId(v.id),//"virtual_1",
                dish_key_id: dish_key_id,//"3143152",
                expansion: v.expansion,
                gbom_qty_high: v.gbom_qty_high,
                gbom_qty_mid: v.gbom_qty_mid,
                bom_qty_high: v.bom_qty_high,
                bom_qty_mid: v.bom_qty_mid,
                material_id: formatId(v.material_id),//360491,
                process_id: formatId(v.process_id),//14,
                unit_id: formatId(v.unit_id),//9,
                // material_sequence_no: v.material_sequence_no//10100,
                material_sequence_no: i + 1,//10100,
                net_material_id: v.net_material_id
            };
            if (_this.state.isGbom) {
                item.bom_qty_high = item.gbom_qty_high * item.expansion;
                item.bom_qty_mid = item.gbom_qty_mid * item.expansion;
            } else {
                item.gbom_qty_high = item.bom_qty_high / item.expansion;
                item.gbom_qty_mid = item.bom_qty_mid / item.expansion;
            }
            data.push(item);
        });
        // console.log(JSON.stringify(data));
        return data;
    }
    getRowData(id) {
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data) {
                if (id) {
                    node.data.id == id && (rowData.push(node.data));
                } else {
                    rowData.push(node.data);
                }
            }
        });
        return rowData;
    }
}
// 菜品BOM 一份
class CreatDishBomOne extends Component {
    static template = xml`
        <div class="mt-3 d-flex gap-3" style="align-items: center;">
            <div style="width: 300px;">
             <div class="input-group">
                <span class="input-group-text">菜品重量</span>
                <input type="number" class="form-control form-control-sm" t-model="state.SettingForm.totalWeight" min="1" style="width: 1% !important;" placeholder="数字" t-on-change="checkSettingForm"/>
                <span class="input-group-text">克</span>
                <button type="button" class="btn btn-primary btn-sm" t-on-click.stop="handleSubmitSetting">修改</button>
              </div>
            </div>
              
            <div style="width: 300px;">
             <div class="input-group">
                <span class="input-group-text">荤</span>
                <input type="number" class="form-control form-control-sm" t-model="state.SettingForm.meatRatio" style="width: 1% !important;" t-on-change="checkSettingForm"/>
                <span class="input-group-text">%，素 <t t-esc="vegetablesRatio"/> % </span>
                <button type="button" class="btn btn-primary btn-sm" t-on-click.stop="handleSubmitSetting">修改</button>
              </div>
            </div>
        </div>
        <div class="d-flex text-danger mt-3" t-if="state.SettingFormMsg">
            <t t-esc="state.SettingFormMsg"/>
        </div>
        <div t-ref="dishWholeGrid" style="width: 100%;height:300px" class="ag-theme-balham myGrid mt-3"/>
    `;
    setup() {
        this.dishWholeGrid_ref = useRef('dishWholeGrid');
        this.pinnedBottomRowData = [{
            id: 'bottom',
        }];
        this.state = useState({
            isGbom:false,
            msg:'',
            SettingFormMsg:'',
            SettingForm:{
                totalWeight:'',
                meatRatio:''
            }
        });
        onMounted(() => {
            let _this = this;
            this.state.isGbom = this.env.getIsGbom();
            this.gridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                suppressRowClickSelection: false,
                columnDefs: [],
                valueCache: 1,
                context: {
                    owl_widget: _this
                },
                getContextMenuItems: (e) => {
                    return _this.setAGMenus(e);
                },
                onGridReady: function (params) {
                    let defaultSortModel = [
                        {colId: 'material_sequence_no', sort: 'asc', sortIndex: 0},
                    ];
                    params.columnApi.applyColumnState({state: defaultSortModel});
                },
                onCellValueChanged: (e) => {
                    // console.log(e);
                    _this.onCellValueChanged(e);
                },
                processDataFromClipboard: () => {
                    return []
                },
                pinnedBottomRowData: _this.pinnedBottomRowData,
                columnTypes: {
                    editableColumn: {
                        editable: (params) => {
                            return _this.isCellEditable(params);
                        },
                    }
                },
                getRowStyle: params => {
                    if (params && params.node && params.node.data && params.node.data.id == 'bottom') {
                        return { background: '#f4f6fa' };
                    }
                },
                // stopEditingWhenCellsLoseFocus:true
            });

            this.dishWholeGrid = new agGrid.Grid(this.dishWholeGrid_ref.el, this.gridOptions);
            this.setColumnDefs();
            this.setRowData(this.props.data.dish_bom||[]);
            this.dish_key_id = this.props.data.dish_key_id;
        });
        onWillUpdateProps(nextProps => {

        });
        useBus(this.env.bus, 'checkWhole', ({detail}) => {
            this.checkWhole();
            detail.msg += this.state.msg;
        });
        useBus(this.env.bus, 'getWhole', ({detail}) => {
            detail.list = this.getSaveData();
        });
        useBus(this.env.bus, 'copyDishBom', ({detail}) => {
            // if(detail.type == 'add'){
            //     this.addRows(detail.bom);
            // }
            if(detail.type == 'copy'){
                this.setRowData(detail.bom,1);
            }
        });
        this.handleSubmitSetting = _.debounce(this.submitSetting, 300);
    }
    static props = {
        is_edit: {type: Boolean, optional: true},
        data:{type: Object, optional: true}
    };
    checkSettingForm() {
        let totalWeight = this.state.SettingForm.totalWeight;
        let meatRatio = this.state.SettingForm.meatRatio;

        if(!(totalWeight+'').trim()){
            this.state.SettingFormMsg = '重量为大于0的正整数';
            return;
        }
        totalWeight = keepTwoDecimal(totalWeight);
        this.state.SettingForm.totalWeight = totalWeight;
        // let regex = /^[1-9]\d*$/;
        // if (!regex.test(totalWeight)) {
        //     this.state.SettingFormMsg = '重量为大于0的正整数';
        //     return;
        // }
        if (!(totalWeight>0)) {
            this.state.SettingFormMsg = '重量为大于0的数字';
            return;
        }
        if(!(meatRatio+'').trim()){
            this.state.SettingFormMsg = '荤比例为0~100的数字';
            return;
        }
        meatRatio = keepTwoDecimal(meatRatio);
        this.state.SettingForm.meatRatio = meatRatio;
        if (meatRatio<0 || meatRatio>100) {
            this.state.SettingFormMsg = '荤比例为0~100的数字';
            return;
        }
        let flag = true;
        let minWeight = 0;
        let minVage = 0;
        let minMeat = 0;
        let meat_length = 0;
        let vage_length = 0;

        this.gridOptions.api.forEachNode((node)=>{
            if (node.data && node.data.material_id) {
                if(!node.data.unit_id){
                    flag = false;
                }
                if(!node.data.qty_high){
                    flag = false;
                }
                if(this.env.getIsMeatMaterial(node.data.material_id)){
                    meat_length ++;
                }else{
                    vage_length ++;
                }
                if(node.data.qty_high && node.data.unit_id){
                    if(this.isIntegerUnitId(node.data.unit_id)){
                        let _w = this.getMaterialKeWeight(node.data.material_id,node.data.unit_id);
                        minWeight += _w;
                        if(this.env.getIsMeatMaterial(node.data.material_id)){
                            minMeat += _w;
                        }else{
                            minVage += _w;
                        }
                    }
                }
            }
        });
        if(vage_length == 0 && meat_length == 0){
            this.state.SettingFormMsg = '当前配比没有食材'
            return;
        }
        if(meatRatio == 0 && meat_length>0){
            this.state.SettingFormMsg = '当前配比有荤菜，荤比例不能为0。'
            return;
        }
        if(meatRatio == 100 && vage_length>0){
            this.state.SettingFormMsg = '当前配比有素菜，荤比例不能为100。'
            return;
        }
        if(vage_length == 0){
            meatRatio = 100;
            this.state.SettingForm.meatRatio = meatRatio;
        }
        if(meat_length == 0){
            meatRatio = 0;
            this.state.SettingForm.meatRatio = meatRatio;
        }
        if(!flag){
            this.state.SettingFormMsg = '请完善表格里食材的数量与单位';
            return;
        }
        minWeight = keepTwoDecimal(minWeight);
        if(minWeight > totalWeight){
            this.state.SettingFormMsg = `重量不得低于最小总克数：${minWeight}`;
            return;
        }
        let _resultMeat = totalWeight*meatRatio*0.01;
        _resultMeat = keepTwoDecimal(_resultMeat);
        if(minMeat > _resultMeat){
            this.state.SettingFormMsg = `荤菜重量不得低于：${minMeat}克，当前计算结果为${_resultMeat}克，请增加重量或调整比例`;
            return;
        }
        let _resultVage = totalWeight - (totalWeight*meatRatio*0.01);
        _resultVage = keepTwoDecimal(_resultVage);
        if(minVage > _resultVage){
            this.state.SettingFormMsg = `素菜重量不得低于：${minVage}克，当前计算结果为${_resultVage}克，请增加重量或调整比例`;
            return;
        }
        this.state.SettingFormMsg = '';
    }
    getMaterialKeWeight(material_id,unit_id,qty){
        !qty && (qty = 1);
        let ratio = this.env.getMaterialUnitJinRatio(material_id,unit_id);
        let ke_ratio = this.env.getMaterialUnitJinRatio(material_id,this.env.get_ke_unit_id());
        let weight_ke = qty * ratio / ke_ratio;
        weight_ke = keepTwoDecimal(weight_ke);
        return weight_ke
    }
    get vegetablesRatio(){
        let ratio = 0;
        try {
            let meatRatio = this.state.SettingForm.meatRatio;
            ratio = 100 - Number(meatRatio);
            ratio = keepTwoDecimal(ratio);
        }catch (e) {}
        return ratio;
    }
    submitSetting(){
        this.checkSettingForm();
        if(this.state.SettingFormMsg){
            return;
        }
        let totalWeight = this.state.SettingForm.totalWeight;
        totalWeight = Number(totalWeight);
        let meatRowNodes = [];
        let vageRowNodes = [];
        let meatRatio = this.state.SettingForm.meatRatio;
        meatRatio = Number(meatRatio)
        let meat_length = 0;
        let vage_length = 0;
        let oldTotalWeight = 0;
        let oldTotalWeightMeat = 0;
        let oldTotalWeightVage = 0;
        // let old_meat_ratio = 0;
        // let old_vage_ratio = 0;
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data && node.data.material_id && node.data.unit_id) {
                if(this.env.getIsMeatMaterial(node.data.material_id)){
                    meat_length++;
                    meatRowNodes.push(node);
                    // old_meat_ratio += node.data.ratio_high;
                    oldTotalWeightMeat += node.data.weight_high;
                }else{
                    vage_length++;
                    vageRowNodes.push(node);
                    // old_vage_ratio += node.data.ratio_high;
                    oldTotalWeightVage += node.data.weight_high;
                }
                oldTotalWeight += node.data.weight_high;
            }
        });
        // let diff = totalWeight - oldTotalWeight;
        let updateRows = [];
        let left = totalWeight;
        let leftMeat = totalWeight * meatRatio * 0.01;
        let leftVage = totalWeight * (100-meatRatio) * 0.01;
        let finalTotalWeight = 0;
        if(meat_length > 0){
            meatRowNodes.sort((a, b) =>{
                let _a = this.isIntegerUnitId(a.data.unit_id) ? 0:1;
                let _b = this.isIntegerUnitId(b.data.unit_id) ? 0:1;
                return _a - _b
            });
            meatRowNodes.forEach((node,index)=>{
                let isLast = false;
                if((index+1) === meat_length){
                    isLast = true;
                }
                let _weight = totalWeight * meatRatio * 0.01 * (node.data.weight_high/oldTotalWeightMeat);
                let data = this.setting_row_item(node.data,_weight,leftMeat,isLast);
                leftMeat -= data.weight_high
                left -= data.weight_high;
                // console.log(left);
                finalTotalWeight += data.weight_high;
                updateRows.push(data);
            });
        }

        if(vage_length > 0){
            vageRowNodes.sort((a, b) =>{
                let _a = this.isIntegerUnitId(a.data.unit_id) ? 0:1;
                let _b = this.isIntegerUnitId(b.data.unit_id) ? 0:1;
                return _a - _b
            });
            vageRowNodes.forEach((node,index)=>{
                let isLast = false;
                if((index+1) === vage_length){
                    isLast = true;
                    if(leftMeat != 0){
                        leftVage += leftMeat
                    }
                }
                let _weight = totalWeight * (100-meatRatio) * 0.01 * (node.data.weight_high/oldTotalWeightVage);
                let data = this.setting_row_item(node.data,_weight,leftVage,isLast);
                leftVage -= data.weight_high;
                left -= data.weight_high;
                finalTotalWeight += data.weight_high;
                updateRows.push(data);
            });
        }
        updateRows.forEach(v=>{
            let ratio = v.weight_high/finalTotalWeight*100;
            ratio = keepTwoDecimal(ratio);
            v.ratio_high = ratio;
            v.ratio_mid = ratio;
        })
        // console.log(updateRows);
        this.gridOptions.api.applyTransaction({update: updateRows},()=>{});
        this.update_ratio_weight();

    }
    // diff差值 left剩下  是否最后一个isLast
    setting_row_item(row,_weight,left,isLast){
        let data = JSON.parse(JSON.stringify(row))
        let { unit_id,material_id,ratio_high,weight_high } = data;
        // ratio_high += diff_ratio;
        // let new_weight_high = weight_high + (diff*ratio_high*0.01);
        let new_weight_high = _weight;
        if(isLast){
            new_weight_high = left
        }
        let unit_ratio = this.env.getMaterialUnitJinRatio(material_id,unit_id);
        let ke_ratio = this.env.getMaterialUnitJinRatio(material_id,this.env.get_ke_unit_id());
        let qty_high = keepTwoDecimal(new_weight_high/unit_ratio*ke_ratio);
        if(this.isIntegerUnitId(unit_id)){
            qty_high = parseInt(qty_high);
            if(qty_high < 1){
                qty_high = 1;
            }
        }else if(qty_high < 0){
            qty_high = 0.01;
        }
        new_weight_high = qty_high/ke_ratio*unit_ratio;
        new_weight_high = keepTwoDecimal(new_weight_high);
        // let ratio = new_weight_high/totalWeight*100;
        // ratio = keepTwoDecimal(ratio);
        data.qty_high = qty_high;
        data.qty_mid = qty_high;
        data.weight_high = new_weight_high;
        data.weight_mid = new_weight_high;

        left -= new_weight_high;
        return data;
    }

    addRows(data){
        let rowData = JSON.parse(JSON.stringify(data));
        rowData.forEach(v=>{
            v.id = add_dish_bom_id();
        });
        this.gridOptions.api.applyTransactionAsync({add: rowData}, (res) => {
            // this.gridOptions.api.redrawRows();
        });
    }

    checkWhole() {
        this.gridOptions.api.stopEditing();
        let rowData = this.getRowData();
        let flag = true;
        rowData.forEach(v => {
            if (!v.material_id) {
                return;
                // this.state.msg = '配比：请选择食材(毛料)';
                // flag = false
            }
            if (!v.unit_id) {
                this.state.msg = '配比：请选择单位；';
                flag = false
            }
            if (!v.process_id) {
                this.state.msg = '配比：请选择工序；';
                flag = false
            }
            if (!this.state.isGbom) {
                if (!v.material_id_net_material_id) {
                    this.state.msg = '配比：请选择食材(净料)；';
                    flag = false
                }
            }
            if(!v.qty_high){
                this.state.msg = '配比：请输入数量';//(套餐)
                flag = false
            }
            // if(!v.qty_mid){
            //     this.state.msg = '配比：请输入(称重)数量';
            //     flag = false
            // }
        });
        if (flag) {
            this.state.msg = ''
        }
        return flag
    }

    get material_item_net_material(){
        let arr = [];
        this.env.getIndex().material_item.forEach(v => {
            arr.push({
                id: v.id + '_' + v.net_material_id,
                name: this.env.getGlobal().net_material[v.net_material_id].name,
                material_name: v.name,
                material_id: v.id,
                net_material_id: v.net_material_id
            })
        });
        return arr;
    }
    get material_item_net_material_obj(){
        return toObj(this.material_item_net_material, 'id');
    }

    setColumnDefs() {
        let isGbom = this.state.isGbom;
        let cols = [
            {
                headerName: '食材(净料)',
                field: 'material_id_net_material_id',
                menuTabs: [],
                flex: 1,
                cellEditor: selectMaterialByNetCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.material_item_net_material
                    };
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.material_item_net_material_obj[params.value].name;
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
                hide: isGbom
            },
            {
                headerName: '食材(毛料)',
                field: 'material_id',
                menuTabs: [],
                flex: 1,
                cellEditor: selectMaterialCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.env.getIndex().material_item
                    };
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().material_item[params.value].name;
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
                cellClassRules: {
                    'bg_gray': (params) => !isGbom
                },
            },
            {
                field: 'net_material_id',
                hide: true
            },
            {
                headerName: '工序',
                field: 'process_id',
                menuTabs: [],
                width: 60,
                cellEditor: selectCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: params.context.owl_widget.env.getIndex().dish_process_category
                    };
                },
                cellRenderer: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().dish_process_category[params.value].name
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
            },
            // {
            //     headerName:'套餐',
            //     children:[]
            // },
            {
                headerName: '比例(%)',
                field: 'ratio_high',
                menuTabs: [],
                width: 50,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true
                        },
                    };
                },
                // type: 'editableColumn',
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                hide:true
            },
            {
                headerName: '克',
                field: 'weight_high',
                menuTabs: [],
                width: 50,
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                valueGetter:(params)=>{
                    if (params.data.id == 'bottom') {
                        return params.context.owl_widget.getTotalWeight('high');
                    } else {
                        return params.data.weight_high||''
                    }
                },
                hide:true
            },
            {
                headerName: '数量',
                field: 'qty_high',
                menuTabs: [],
                width: 60,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    if(params.context.owl_widget.isIntegerUnitId(params.data.unit_id)){
                        return {
                            values: {
                                decimal: false
                            },
                        };
                    }else{
                        return {
                            values: {
                                decimal: true,
                                toFixed:2
                            },
                        };
                    }
                },
                type: 'editableColumn',
                valueGetter:(params)=>{
                    if (params.data.id == 'bottom') {
                        return '';
                    } else {
                        return params.data.qty_high||''
                    }
                }
            },
            {
                headerName: '单位',
                field: 'unit_id',//unit_id  diff_purchase_unit_id
                menuTabs: [],
                width: 60,
                cellEditor: unitCellEditor,
                // cellEditor: selectCellEditor,
                cellEditorParams: (params) => {
                    let material_id = params.data.material_id;
                    let values = [];
                    values.push({
                        id:params.context.owl_widget.env.get_ke_unit_id(),
                        name:'克'
                    })
                    if (material_id) {
                        values = values.concat(params.context.owl_widget.env.searchUnit(material_id));
                    }
                    return {
                        values: values,
                        material_id: material_id
                    };
                },
                cellRenderer: params => {
                    if (params.value && params.value != '') {
                        if(params.value == params.context.owl_widget.env.get_ke_unit_id()){
                            return '克'
                        }
                        return params.context.owl_widget.env.getGlobal().material_purchase_unit_category[params.value].name
                    } else {
                        return ''
                    }
                },
                type: 'editableColumn',
            },
            {
                headerName: '比例(%)',
                field: 'ratio_mid',
                menuTabs: [],
                width: 50,
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                hide:true
            },
            {
                headerName: '克',
                field: 'weight_mid',
                menuTabs: [],
                width: 50,
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                valueGetter:(params)=>{
                    if (params.data.id == 'bottom') {
                        return params.context.owl_widget.getTotalWeight('mid');
                    } else {
                        return params.data.weight_mid||''
                    }
                },
                hide:true
            },
            {
                headerName: '数量',
                field: 'qty_mid',
                menuTabs: [],
                width: 50,
                cellEditor: numberCellEditor,
                cellEditorParams: (params) => {
                    return {
                        values: {
                            decimal: true,
                            toFixed:2
                        },
                    };
                },
                type: 'editableColumn',
                valueGetter:(params)=>{
                    if (params.data.id == 'bottom') {
                        return '';
                    } else {
                        return params.data.qty_mid||''
                    }
                },
                hide:true
            },
            {
                headerName: '价格',
                field: 'price_mid',
                menuTabs: [],
                width: 50,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.calculatePrice(params.data,'mid');
                    return value;
                },
                valueFormatter: params => {
                    if ((params.data && params.data.material_id)||params.data.id == 'bottom') {
                        return params.value;
                    } else {
                        return ''
                    }
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                hide:true
            },
            // {
            //     headerName: '称重',
            //     children: []
            // },
            {
                headerName: '单价',
                field: 'unit_price',
                menuTabs: [],
                width: 60,
                valueGetter: (params) => {
                    if ((params.data && params.data.material_id && params.data.unit_id)) {
                        let material_id = params.data.material_id;
                        let unit_id = params.data.unit_id;
                        return params.context.owl_widget.env.getMaterialPrice(material_id,unit_id,1)
                    }else{
                        return 0
                    }
                },
                valueFormatter: params => {
                    if ((params.data && params.data.material_id)) {
                        return params.value;
                    } else {
                        return ''
                    }
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                hide:true
            },
            {
                headerName: '采购价',
                field: 'purchase_unit_price',
                menuTabs: [],
                width: 80,
                valueGetter: (params) => {
                    let value = '';
                    if ((params.data && params.data.material_id)) {
                        try{
                            let material_id = params.data.material_id;
                            let purchase_unit_price = params.context.owl_widget.env.getGlobal().material_item[material_id].purchase_unit_price;
                            let purchase_unit_id = params.context.owl_widget.env.getGlobal().material_item[material_id].purchase_unit_id;
                            let purchase_unit_name = params.context.owl_widget.env.getGlobal().material_purchase_unit_category[purchase_unit_id].name;
                            return `${purchase_unit_price}/${purchase_unit_name}`
                        }catch (e) {
                            return ''
                        }
                    }else{
                        return ''
                    }
                },
                // valueFormatter: params => {
                //     if ((params.data && params.data.material_id)) {
                //         return params.value;
                //     } else {
                //         return ''
                //     }
                // },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
            },
            {
                headerName: '成本',
                field: 'price_high',
                menuTabs: [],
                width: 60,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.calculatePrice(params.data,'high');
                    return value;
                },
                valueFormatter: params => {
                    if ((params.data && params.data.material_id)||params.data.id == 'bottom') {
                        return params.value;
                    } else {
                        return ''
                    }
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                type: 'editableColumn',
            },
            {
                headerName: '荤/素',
                field: 'meat_vegetables',
                menuTabs: [],
                width: 60,
                valueGetter: (params) => {
                    if ((params.data && params.data.material_id)) {
                        let material_id = params.data.material_id;
                        return this.env.getIsMeatMaterial(material_id)?'meat':'vegetables';
                    }else{
                        return ''
                    }
                },
                valueFormatter: params => {
                    if(params.value == 'meat'){
                        return '荤'
                    }
                    if(params.value == 'vegetables'){
                        return '素'
                    }
                    return ''
                },
                editable: false,
                cellClassRules: {
                    'bg_gray': (params) => true
                },
            },

            {
                field: 'material_sequence_no',
                hide: true
            },

        ];
        this.gridOptions.api.setColumnDefs(cols);
    }

    get_dish_bom_to_one(dish_bom){
        let data = [];
        let totalWeight_high = 0;
        let totalWeight_mid = 0;
        let meatRatio = 0;
        let isGbom = this.state.isGbom;
        dish_bom.forEach(v=>{
            let {id,gbom_qty_high, gbom_qty_mid,bom_qty_high, bom_qty_mid,material_id,net_material_id,material_sequence_no,process_id,unit_id} = v;
            let item = {
                id,material_id,net_material_id,material_sequence_no,process_id,unit_id
            };
            let qty_hign = isGbom?gbom_qty_high:bom_qty_high;
            let qty_mid = isGbom?gbom_qty_mid:bom_qty_mid;
            let ratio = this.env.getMaterialUnitJinRatio(material_id,unit_id);
            let ke_ratio = this.env.getMaterialUnitJinRatio(material_id,this.env.get_ke_unit_id());
            let weight_high = qty_hign * 0.01 * ratio / ke_ratio;
            let weight_mid = qty_mid * 0.01 * ratio / ke_ratio;
            if(item.unit_id == this.env.get_jin_unit_id()){
                item.qty_high = keepTwoDecimal(qty_hign * 0.01 / ke_ratio);
                item.qty_mid = keepTwoDecimal(qty_mid * 0.01 / ke_ratio);
                item.unit_id = this.env.get_ke_unit_id();
            }else{
                item.qty_high = keepTwoDecimal(qty_hign * 0.01);
                item.qty_mid = keepTwoDecimal(qty_mid * 0.01 );
            }
            if(this.isIntegerUnitId(item.unit_id)){
                item.qty_high = parseInt(item.qty_high);
                item.qty_mid = parseInt(item.qty_mid);
            }
            item.weight_high = keepTwoDecimal(weight_high);
            item.weight_mid = keepTwoDecimal(weight_mid);
            totalWeight_high += item.weight_high;
            totalWeight_mid += item.weight_mid;
            data.push(item);
        })
        data.forEach(item=>{
            item.ratio_high = item.weight_high/totalWeight_high * 100;
            item.ratio_high = keepTwoDecimal(item.ratio_high);
            item.ratio_mid = item.weight_mid/totalWeight_mid * 100;
            item.ratio_mid = keepTwoDecimal(item.ratio_mid);
            if(this.env.getIsMeatMaterial(item.material_id)){
                meatRatio += item.ratio_high;
            }
        });
        // console.log(data);
        this.state.SettingForm.totalWeight = totalWeight_high;
        this.state.SettingForm.meatRatio = keepTwoDecimal(meatRatio);
        return data;
    }
    // 是只能整数的单位
    isIntegerUnitId(unit_id){
        let flag = false;
        if(unit_id === this.env.get_jin_unit_id() || unit_id === this.env.get_ke_unit_id()){
            flag = false
        }else{
            flag = true
        }
        return flag;
    }

    setRowData(dish_bom,isCopy) {
        let _dish_bom = JSON.parse(JSON.stringify(dish_bom));
        let data = this.get_dish_bom_to_one(_dish_bom);
        data.forEach((v, i) => {
            if (!v.material_sequence_no) {
                v.material_sequence_no = i + 1
            }
            if(isCopy){
                v.id = add_dish_bom_id();
            }
            v.material_sequence_no = v.material_sequence_no * 100;
            if (!v.net_material_id) {
                v.net_material_id = this.env.getGlobal().material_item[v.material_id].net_material_id;
            }
            v.material_id_net_material_id = v.material_id + '_' + v.net_material_id;
        });
        // console.log(dish_bom);
        let _l = data.length;
        if(_l < 15){
            let default_process_id = this.env.getGlobal().default_process_id;
            for (let i = _l;i<15;i++) {
                data.push({
                    id: add_dish_bom_id(),
                    material_id: '',
                    process_id: '',//默认 ‘无’
                    unit_id: '',
                    net_material_id: '',
                    material_sequence_no:(i+1) * 100,
                    weight_high:'',
                    weight_mid:'',
                    ratio_high:'',
                    ratio_mid:'',
                    qty_high:'',
                    qty_mid:''
                })
            }
        }
        // data.sort((a,b)=>{return a.material_sequence_no-b.material_sequence_no});//排序
        this.gridOptions.api.setRowData(data);
        this.gridOptions.api.redrawRows();
        this.checkWhole();
    }

    // 配比部分
    isCellEditable(params) {
        let flag = true;
        let data = params.data;
        let colId = params.colDef.field;
        if (data.id == 'bottom') {
            flag = false;
        }
        if (colId == 'material_id' && !this.state.isGbom) {
            flag = false;
        }
        return flag;
    }

    // 单元格改变
    onCellValueChanged(params) {
        // console.log('-----onCellValueChanged----');
        // console.log(params);
        if (params.source == "edit" && params.colDef.field == "material_id") {
            this.onMaterialChanged(params);
        }else if(params.colDef.field == "material_id" && !params.value){
            let updateRowData = [params.node.data];
            updateRowData[0].process_id = '';
            updateRowData[0].unit_id = '';
            updateRowData[0].net_material_id = '';
            updateRowData[0].ratio_high = '';
            updateRowData[0].weight_high = '';
            updateRowData[0].qty_high = '';
            updateRowData[0].ratio_mid = '';
            updateRowData[0].weight_mid = '';
            updateRowData[0].qty_mid = '';
            this.gridOptions.api.applyTransaction({update: updateRowData},()=>{});
        }
        if (params.source == "edit" && params.colDef.field == "material_id_net_material_id") {
            let id = params.newValue;
            let net_material_id = this.material_item_net_material_obj[id].net_material_id;
            let material_id = this.material_item_net_material_obj[id].material_id;

            params.node.setDataValue('net_material_id', net_material_id);
            params.node.setDataValue('material_id', material_id);

            // let unit_id = this.material_item[material_id].main_unit_id;
            let unit_id = this.env.get_ke_unit_id();
            if (unit_id != params.data.unit_id) {
                params.node.setDataValue('unit_id', unit_id);
            }
        }else if(params.colDef.field == "material_id_net_material_id" && !params.value){
            let updateRowData = [params.node.data];
            updateRowData[0].process_id = '';
            updateRowData[0].unit_id = '';
            updateRowData[0].material_id = '';
            updateRowData[0].ratio_high = '';
            updateRowData[0].weight_high = '';
            updateRowData[0].qty_high = '';
            updateRowData[0].ratio_mid = '';
            updateRowData[0].weight_mid = '';
            updateRowData[0].qty_mid = '';
            this.gridOptions.api.applyTransaction({update: updateRowData},()=>{});
        }
        if (params.source == "edit" && params.colDef.field.startsWith('weight_')) {
            // this.onWeightChanged(params)
        }
        if (params.source == "edit" && params.colDef.field.startsWith('ratio_')) {
            // this.onRatioChanged(params);
        }
        if (params.source == "edit" && params.colDef.field.startsWith('qty_')) {
            this.onQtyChanged(params);
        }
        if (params.source == "edit" && params.colDef.field == 'unit_id') {
            this.onUnitIdChanged(params);
        }
        this.checkWhole();
        this.env.setMsg(this.state.msg);
        params.source && this.update_ratio_weight();
        this.state.SettingFormMsg = '';
    }
    onQtyChanged(params){
        let [type,key] = params.colDef.field.split('_');
        if(key == 'high'){
            params.node.setDataValue('qty_mid', params.newValue);
        }
    }
    onUnitIdChanged(params){

    }
    // 更新克数和比例
    update_ratio_weight(){
        let rowData = [];
        let total_weight_high = 0;
        let total_weight_mid = 0;
        let meatRatio = 0;
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data && node.data.material_id && node.data.unit_id) {
                let data = JSON.parse(JSON.stringify(node.data));
                let {material_id,unit_id,qty_high,qty_mid} = data;
                qty_high = Number(qty_high)||0;
                qty_mid = Number(qty_mid)||0;
                let ratio = this.env.getMaterialUnitJinRatio(material_id,unit_id);
                let ke_ratio = this.env.getMaterialUnitJinRatio(material_id,this.env.get_ke_unit_id());
                if(qty_high){
                    data.weight_high = keepTwoDecimal(qty_high * ratio /ke_ratio);
                    total_weight_high += data.weight_high;
                }
                if(qty_mid){
                    data.weight_mid = keepTwoDecimal(qty_mid * ratio/ke_ratio);
                    total_weight_mid += data.weight_mid;
                }
                rowData.push(data);
            }
        });
        rowData.forEach(v=>{
            v.ratio_high = keepTwoDecimal(v.weight_high/total_weight_high*100);
            v.ratio_mid = keepTwoDecimal(v.weight_mid/total_weight_mid*100);
            if(this.env.getIsMeatMaterial(v.material_id)){
                meatRatio += v.ratio_high;
            }
        })
        this.gridOptions.api.applyTransaction({update: rowData},()=>{});

        this.state.SettingForm.totalWeight = keepTwoDecimal(total_weight_high);
        this.state.SettingForm.meatRatio = keepTwoDecimal(meatRatio);
    }
    // 弃用
    onWeightChanged(params){
        let [type,key] = params.colDef.field.split('_');
        let totalWeight = this.getTotalWeight(key);
        let totalWeight_mid = 0;
        if(key == 'high'){
            params.node.setDataValue('weight_mid', params.newValue);
            totalWeight_mid = this.getTotalWeight('mid');
            console.log(totalWeight_mid);
        }
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data && node.data.material_id && node.data[`weight_${key}`]) {
                let ratio = node.data[`weight_${key}`]/totalWeight * 100;
                ratio = keepTwoDecimal(ratio);
                node.setDataValue(`ratio_${key}`,ratio);
            }
            if(key == 'high'){
                if (node.data && node.data.material_id && node.data[`weight_mid`]) {
                    let ratio = node.data[`weight_mid`]/totalWeight_mid * 100;
                    ratio = keepTwoDecimal(ratio);
                    node.setDataValue(`ratio_mid`,ratio);
                }
            }
        });
    }
    // 暂不用
    onRatioChanged(params){
        let totalWeight = this.getTotalWeight();
        let ratio = params.newValue;
        params.node.setDataValue('weight',totalWeight*ratio*0.01);
        let diff = (params.newValue||0) - (params.oldValue||0);
        let _length = 0;
        let rowNodes = [];
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data && node.data.material_id && node.data.id != params.data.id) {
                rowNodes.push(node);
                _length++
            }
        });
        if(diff == 0){
            return;
        }
        if(_length == 0){
            params.node.setDataValue('ratio',100);
            return;
        }
        let diffRatio = diff/_length;
        let totalRatio= 100 - ratio;
        rowNodes.forEach((node,i)=>{
            let _ratio = node.data.ratio - diffRatio;
            if(i == (rowNodes.length-1)){
                _ratio = totalRatio;
            }
            totalRatio -= _ratio;
            node.setDataValue('ratio',_ratio);
            node.setDataValue('weight',totalWeight * _ratio * 0.01);
        })
    }

    onMaterialChanged(params) {
        // console.log('-----onMaterialChanged----');
        let data = params.node.data;
        let material_id = params.newValue;
        // let unit_id = this.env.getGlobal().material_item[material_id].main_unit_id;
        let unit_id = this.env.get_ke_unit_id();
        if (unit_id != data.unit_id) {
            params.node.setDataValue('unit_id', unit_id);
        }
        let net_material_id = this.env.getGlobal().material_item[material_id].net_material_id;
        params.node.setDataValue('net_material_id', net_material_id);

        if(material_id){
            // if(!data.expansion){
            //     params.node.setDataValue('expansion', 1);
            // }
            if(!data.process_id){
                let default_process_id = this.env.getGlobal().default_process_id;
                params.node.setDataValue('process_id', default_process_id);
            }
        }
    }

    getTotalWeight(key){
        let rowData = this.getRowData();
        let totalWeight = 0;
        rowData.forEach(v=>{
            if(v.material_id && v[`weight_${key}`]){
                totalWeight += v[`weight_${key}`];
            }
        })
        return totalWeight;
    }

    // 右键菜单
    setAGMenus(e) {
        // console.log('-------setAGMenus-------');
        // console.log(e);
        let node = e.node || {};
        // if (!node.data) {
        //     return;
        // }
        // if(!e.column){
        //     return;
        // }
        let _this = this;
        let menu = [
            {
                name: '新增一行',
                action: () => {
                    _this.addRow(node, 'down');
                }
            },
        ];
        if (node.data) {
            menu = [
                {
                    name: '向下新增一行',
                    action: () => {
                        _this.addRow(node, 'down');
                    },
                },
                {
                    name: '向上新增一行',
                    action: () => {
                        _this.addRow(node, 'up');
                    }
                },
                {
                    name: '删除本行',
                    action: () => {
                        _this.removeRow(node);
                    },
                    cssClasses: ['text-danger'],
                }
            ];
            if(node.data.material_id){
                menu.push({
                    name: '食材详情',
                    action: () => {
                        _this.env.openCreatMaterialModal({
                            id: node.data.material_id
                        },()=>{
                            _this.gridOptions.api.refreshCells({force: true});//刷新表格
                        });
                    },
                    cssClasses: ['text-success'],
                })
            }
        }
        return menu;
    }

    removeRow(node) {
        let data = node.data;
        this.gridOptions.api.applyTransactionAsync({remove: [data]}, (res) => {
            this.gridOptions.api.redrawRows();
            this.update_ratio_weight();
        });
    }

    addRow(node, direction) {
        let default_process_id = this.env.getGlobal().default_process_id;
        let data = node.data || {material_sequence_no: 100};
        let newItem = {
            id: add_dish_bom_id(),
            ratio_high:'',
            weight_high:'',
            qty_high:'',
            ratio_mid:'',
            weight_mid:'',
            qty_mid:'',
            material_id: '',
            process_id: '',//默认 ‘无’
            unit_id: '',
            net_material_id: ''
        };
        if (direction == 'up') {
            newItem.material_sequence_no = data.material_sequence_no - 1;
        }
        if (direction == 'down') {
            newItem.material_sequence_no = data.material_sequence_no + 1;
        }
        // console.log(newItem);
        this.gridOptions.api.applyTransactionAsync({add: [newItem]}, (res) => {
            this.gridOptions.api.redrawRows();
        });
    }

    calculatePrice(data,key) {
        let price = 0;
        if (data.id == 'bottom') {
            // 底部总价
            let rowData = this.getRowData();
            let result = [];
            rowData.forEach(v => {
                result.push(this.calculatePrice(v,key));
            });
            let sum = eval(result.join("+"));
            price = formatPrice(sum);
            // console.log(price);
        } else {
            let {material_id,unit_id} = data;
            if(data[`qty_${key}`] && material_id && unit_id){
                price = this.env.getMaterialPrice(material_id,unit_id,data[`qty_${key}`]);
                price = formatPrice(price);
            }
            // price = this.env.getDishBomPrice(data);
        }
        return price;
    }
    getSaveData() {
        let _this = this;
        let data = [];
        let rowData = this.getRowData();
        let dish_key_id = formatId(this.dish_key_id);
        rowData.sort((a, b) => a.material_sequence_no - b.material_sequence_no);
        rowData.forEach((v,i)=>{
            if(!v.material_id){
                return;
            }
            let unit_id = formatId(v.unit_id);
            let gbom_qty_high = v.qty_high*100;
            if(!v.qty_mid){
                v.qty_mid = v.qty_high;
            }
            let gbom_qty_mid = v.qty_mid*100;
            if(unit_id == this.env.get_ke_unit_id()){
                unit_id = this.env.get_jin_unit_id();
                gbom_qty_high = gbom_qty_high/500;
                gbom_qty_mid = gbom_qty_mid/500;
            }
            let item = {
                id: formatId(v.id),//"virtual_1",
                dish_key_id: dish_key_id,//"3143152",
                expansion: 1,
                gbom_qty_high: gbom_qty_high,
                gbom_qty_mid: gbom_qty_mid,
                bom_qty_high: gbom_qty_high,
                bom_qty_mid: gbom_qty_mid,
                material_id: formatId(v.material_id),//360491,
                process_id: formatId(v.process_id),//14,
                unit_id: unit_id,
                material_sequence_no: i + 1,//10100,
                net_material_id: v.net_material_id
            };
            // if (_this.state.isGbom) {
            //     item.bom_qty_high = item.gbom_qty_high * item.expansion;
            //     item.bom_qty_mid = item.gbom_qty_mid * item.expansion;
            // } else {
            //     item.gbom_qty_high = item.bom_qty_high / item.expansion;
            //     item.gbom_qty_mid = item.bom_qty_mid / item.expansion;
            // }
            data.push(item);
        });
        // console.log(JSON.stringify(data));
        return data;
    }
    getRowData(id) {
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data) {
                if (id) {
                    node.data.id == id && (rowData.push(node.data));
                } else {
                    rowData.push(node.data);
                }
            }
        });
        return rowData;
    }
}

// 平台菜品BOM
class CreatDishPlat extends Component {
    static template = xml`
        <div class="d-flex align-items-center gap-3 mt-3"  t-if="props.data.length>0">
            <div class="fw-bolder">
               【复制】将使原配比数据删除，请谨慎操作。
            </div>
        </div>
        <div t-ref="dishPlatGrid" style="width: 100%;height:300px" class="ag-theme-balham myGrid mt-3"/>       
    `;
    setup() {
        this.dishPlatGrid_ref = useRef('dishPlatGrid');
        this.rowData = [];
        this.state = useState({
            isGbom:false,
            msg:'',
        });
        onMounted(() => {
            // console.log('dishPlatGrid-onMounted');
            let _this = this;
            this.state.isGbom = this.env.getIsGbom();
            this.gridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                suppressRowClickSelection: false,
                columnDefs: [],
                valueCache: 1,
                context: {
                    owl_widget: _this
                },
                getContextMenuItems: (e) => {
                    return [];
                },
                onGridReady: function (params) {},
                processDataFromClipboard: () => {
                    return []
                },
                getRowStyle: params => {}
            });

            this.dishPlatGrid = new agGrid.Grid(this.dishPlatGrid_ref.el, this.gridOptions);
            this.setColumnDefs();
            // console.log('dishPlatGrid');
            // console.log(this.props.data);
            this.setRowData(this.props.data);
        });
    }
    static props = {
        data:{type: Array, optional: true}
    };

    get material_item_net_material(){
        let arr = [];
        this.env.getIndex().material_item.forEach(v => {
            arr.push({
                id: v.id + '_' + v.net_material_id,
                name: this.env.getGlobal().net_material[v.net_material_id].name,
                material_name: v.name,
                material_id: v.id,
                net_material_id: v.net_material_id
            })
        });
        return arr;
    }
    get material_item_net_material_obj(){
        return toObj(this.material_item_net_material, 'id');
    }

    handleAction(data){
        let _this = this;
        let creat_materials = [];
        let material_item_mmid = toObj(this.env.getIndex().material_item,'mm_id');
        let material_map = this.env.getGlobal().material_map;
        data.bom.forEach(v=>{
            let {bom_qty,unit_id,process_map_id,material_map_id} = v;
            if(material_item_mmid[material_map_id]){

            }else{
                let creat_materials_mmids = creat_materials.map(d=>d.mm_id);
                if(!creat_materials_mmids.includes(material_map_id)){
                    creat_materials.push({
                        mm_id:material_map_id,
                        name:material_map[material_map_id].name
                    });
                }
            }
        });

        let default_process_id = this.env.getGlobal().default_process_id;
        let dish_process_map = this.env.getGlobal().dish_process_map;
        let fn =()=>{
            let material_item_mmid = toObj(this.env.getIndex().material_item,'mm_id');
            let copyBom = [];
            data.bom.forEach(v=>{
                let {bom_qty,unit_id,process_map_id,material_map_id} = v;

                let material_id = material_item_mmid[material_map_id].id;
                let net_material_id = material_item_mmid[material_map_id].net_material_id;
                let process_id = default_process_id;
                try {
                    process_id = _this.env.getIndex().dish_process_category.find(d=>d.name == dish_process_map[process_map_id].name).id;
                }catch (e) {}
                bom_qty = keepTwoDecimal(bom_qty);

                let item = {
                    expansion: 1,
                    gbom_qty_high: bom_qty,
                    gbom_qty_mid: bom_qty,
                    bom_qty_high: bom_qty,
                    bom_qty_mid: bom_qty,
                    material_id: material_id,
                    process_id: process_id,
                    unit_id: unit_id,
                    net_material_id: net_material_id,
                };
                copyBom.push(item);
            });
            this.env.copyDishBom(copyBom,'copy');
        };


        if(creat_materials.length>0){
            let name = creat_materials.map(v=>v.name);
            this.env.openToast({
                msg:'复制该配比将会创建食材：'+name.join('、')+'，是否继续？',
                isCancel:true,
                confirmBtnText:'创建食材并复制配比',
                onConfirm:async ()=>{
                    await _this.env.addBatchMaterialAsync(creat_materials);
                    fn();
                }
            });
        }else{
            fn();
        }
    }

    setColumnDefs() {
        // let isGbom = this.state.isGbom;
        let cols = [
            {
                headerName: '配比',
                field: 'bom_str',
                menuTabs: [],
                flex: 1,
                editable: false,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.getBomStr(params.data.bom||[]);
                    return value;
                },
            },
            // {
            //     headerName: '(元)成本',
            //     field: 'price',
            //     menuTabs: [],
            //     width: 60,
            //     editable: false,
            //     valueGetter: (params) => {
            //         let value = params.context.owl_widget.calculatePrice(params.data.bom);
            //         return value;
            //     },
            // },
            {
                field: 'material_sequence_no',
                hide: true
            },
            {
                headerName: '操作',
                field: 'action',
                menuTabs: [],
                width: 60,
                cellRenderer:actionCellRenderer,
                editable: false
            }
        ];
        this.gridOptions.api.setColumnDefs(cols);
    }

    setRowData(plat_bom_list) {
        let data = JSON.parse(JSON.stringify(plat_bom_list));
        let rowData = [];
        let addId = 1;
        data.forEach((v) => {
            let rowItem = {
                id:addId,
                bom:v
            };
            // v.forEach((d,i) => {
            //     let process_id = default_process_id;
            //     let material_id = '';
            //     let net_material_id = '';
            //     try {
            //         process_id = dish_process_category_obj[d.process_map_id].id;
            //         material_id = material_item_mmid_obj[d.material_map_id].id;
            //         net_material_id = material_item_mmid_obj[d.material_map_id].net_material_id;
            //     }catch (e) {}
            //     let bom_qty = keepTwoDecimal(d.bom_qty);
            //     let item = {
            //         expansion:1,
            //         gbom_qty_high: bom_qty,
            //         gbom_qty_mid: bom_qty,
            //         bom_qty_high: bom_qty,
            //         bom_qty_mid: bom_qty,
            //         material_id: material_id,
            //         process_id: process_id,
            //         unit_id: d.unit_id,
            //         net_material_id: net_material_id,
            //         material_sequence_no:i+1
            //     };
            //     rowItem.bom.push(item);
            // });
            rowData.push(rowItem);
            addId++;
        });
        this.rowData = rowData;
        this.gridOptions.api.setRowData(rowData);
        // this.gridOptions.api.redrawRows();
    }
    getBomStr(bom){
        // let default_process_id = this.env.getGlobal().default_process_id;
        let material_map = this.env.getGlobal().material_map;
        let dish_process_map = this.env.getGlobal().dish_process_map;
        let material_purchase_unit_category = this.env.getGlobal().material_purchase_unit_category;
        let strs = [];
        bom.forEach(v=>{
            let {bom_qty,unit_id,process_map_id,material_map_id} = v;
            let str = '';
            try {
                let name = material_map[material_map_id].name.split('-')[0];
                str += name;
                if(dish_process_map[process_map_id].name != '无'){
                    str += dish_process_map[process_map_id].name;
                }
                str += keepTwoDecimal(bom_qty);
                str += material_purchase_unit_category[unit_id].name;
            }catch (e) {}
            strs.push(str);
        })
        return strs.join('，')
    }
    // calculatePrice(data) {
    //     let price = 0;
    //     let result = [];
    //     data.forEach(v => {
    //         result.push(this.env.getDishBomPrice(v));
    //     });
    //     let sum = eval(result.join("+"));
    //     price = formatPrice(sum);
    //     return price;
    // }
    getRowData(id) {
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data) {
                if (id) {
                    node.data.id == id && (rowData.push(node.data));
                } else {
                    rowData.push(node.data);
                }
            }
        });
        return rowData;
    }
}
// 相似菜品BOM
class CreatDishSimilar extends Component {
    static template = xml`
        <div class="d-flex align-items-center gap-3 mt-3" t-if="props.data.length>0">
            <div class="fw-bolder">
               【复制】将使原配比数据删除，请谨慎操作。
            </div>
        </div>
        <div t-ref="dishSimilarGrid" style="width: 100%;height:300px" class="ag-theme-balham myGrid mt-3"/>
        
    `;
    setup() {
        this.dishSimilarGrid_ref = useRef('dishSimilarGrid');
        this.rowData = [];
        this.state = useState({
            isGbom:false,
            msg:'',
        });
        onMounted(() => {
            let _this = this;
            this.state.isGbom = this.env.getIsGbom();
            this.gridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                suppressRowClickSelection: false,
                columnDefs: [],
                valueCache: 1,
                context: {
                    owl_widget: _this
                },
                getContextMenuItems: (e) => {
                    return [];
                },
                onGridReady: function (params) {

                },
                processDataFromClipboard: () => {
                    return []
                },
                pinnedBottomRowData: _this.pinnedBottomRowData,
                getRowStyle: params => {

                }
            });
            this.dishSimilarGrid = new agGrid.Grid(this.dishSimilarGrid_ref.el, this.gridOptions);
            this.setColumnDefs();

            let dish_key_ids = this.props.data;
            if(dish_key_ids.length == 0){
                this.state.dish_key_name = '暂无相似菜品';
            }else{
                // this.state.dish_key_name = '菜品名称：'+this.env.getGlobal().dish_key[dish_key_id].name;
                this.setRowData(dish_key_ids);
            }
        });
    }
    static props = {
        data:{type: Array, optional: true}
    };

    get material_item_net_material(){
        let arr = [];
        this.env.getIndex().material_item.forEach(v => {
            arr.push({
                id: v.id + '_' + v.net_material_id,
                name: this.env.getGlobal().net_material[v.net_material_id].name,
                material_name: v.name,
                material_id: v.id,
                net_material_id: v.net_material_id
            })
        });
        return arr;
    }
    get material_item_net_material_obj(){
        return toObj(this.material_item_net_material, 'id');
    }

    handleAction(data){
        this.env.copyDishBom(data.bom,'copy');
    }

    setColumnDefs() {
        // let isGbom = this.state.isGbom;
        let cols = [
            {
                headerName: '菜品名称',
                field: 'dish_key_name',
                menuTabs: [],
                width: 100,
                editable: false,
                valueGetter: (params) => {
                    let name = params.context.owl_widget.env.getGlobal().dish_key[params.data.id].name;
                    return name;
                }
            },
            {
                headerName: '配比',
                field: 'bom_str',
                menuTabs: [],
                flex: 1,
                editable: false,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.getBomStr(params.data.bom||[]);
                    return value;
                },
            },
            {
                headerName: '(元)成本',
                field: 'price',
                menuTabs: [],
                width: 60,
                editable: false,
                valueGetter: (params) => {
                    let value = params.context.owl_widget.calculatePrice(params.data.bom||[]);
                    return value;
                },
            },
            {
                field: 'material_sequence_no',
                hide: true
            },
            {
                headerName: '操作',
                field: 'action',
                menuTabs: [],
                width: 60,
                cellRenderer:actionCellRenderer,
                editable: false
            }
        ];
        this.gridOptions.api.setColumnDefs(cols);
    }

    setRowData(dish_key_ids) {
        let ids = JSON.parse(JSON.stringify(dish_key_ids));
        let rowData = [];
        ids.forEach(id=>{
            let bom = this.env.getIndex().dish_bom.filter(v => v.dish_key_id + '' == id + '');
            let item = {
                id,
                bom
            };
            rowData.push(item);
        });
        this.rowData = rowData;
        this.gridOptions.api.setRowData(rowData);
        // this.gridOptions.api.redrawRows();
    }
    getBomStr(bom){
        let default_process_id = this.env.getGlobal().default_process_id;
        let material_item = this.env.getGlobal().material_item;
        let dish_process_category = this.env.getGlobal().dish_process_category;
        let material_purchase_unit_category = this.env.getGlobal().material_purchase_unit_category;
        let strs = [];
        bom.forEach(v=>{
            let {material_id,process_id,unit_id,gbom_qty_high} = v;
            let str = '';
            try {
                let name = material_item[material_id].name.split('-')[0];
                str += name;
                if(dish_process_category[process_id].name != '无'){
                    str += dish_process_category[process_id].name;
                }
                str += gbom_qty_high;
                str += material_purchase_unit_category[unit_id].name;
            }catch (e) {}
            strs.push(str);
        })
        return strs.join('，')
    }
    calculatePrice(data) {
        let price = 0;
        let result = [];
        data.forEach(v => {
            let {gbom_qty_high,unit_id,material_id} = v;
            if(gbom_qty_high && unit_id && material_id){
                price = this.env.getMaterialPrice(material_id,unit_id,gbom_qty_high);
                price = price*0.01;
                price = formatPrice(price);
            }

            // result.push(this.env.getDishBomPrice(v));
            result.push(price);
        });
        let sum = eval(result.join("+"));
        price = formatPrice(sum);
        return price;
    }

    getRowData(id) {
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode((node)=>{
            if (node.data) {
                if (id) {
                    node.data.id == id && (rowData.push(node.data));
                } else {
                    rowData.push(node.data);
                }
            }
        });
        return rowData;
    }
}

class CreatDishModal extends Component {
    static template = xml`
    <!-- 创建菜品 Modal -->
        <div class="modal fade" id="creatDishModal" tabindex="-1">
            <div class="modal-dialog modal-lg  modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
<!--                            <t t-if="props.is_edit">修改菜品</t>-->
<!--                            <t t-if="!props.is_edit">创建菜品</t>-->
                            <t t-esc="state.headerName"/>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">                    
                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                          <li class="nav-item" role="presentation">
                            <button class="nav-link" id="home-tab" data-bs-toggle="tab" data-bs-target="#home-tab-pane" type="button" role="tab" aria-controls="home-tab-pane" aria-selected="true">基本</button>
                          </li>
                          <li class="nav-item" role="presentation">
                            <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile-tab-pane" type="button" role="tab" aria-controls="profile-tab-pane" aria-selected="false">配比</button>
                          </li>
                          <li class="nav-item" role="presentation">
                            <button class="nav-link" id="plat-tab" data-bs-toggle="tab" data-bs-target="#plat-tab-pane" type="button" role="tab" aria-controls="plat-tab-pane" aria-selected="false">平台菜品</button>
                          </li>
                          <li class="nav-item" role="presentation">
                            <button class="nav-link" id="similar-tab" data-bs-toggle="tab" data-bs-target="#similar-tab-pane" type="button" role="tab" aria-controls="similar-tab-pane" aria-selected="false">相似菜品</button>
                          </li>
                        </ul>
                        <div class="tab-content" id="myTabContent" style="min-height: 253px">
                          <div class="tab-pane fade" id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab" tabindex="0">
                            <CreatDishForm is_edit="props.is_edit" data="state.creatDishForm" t-if="props.is_open"></CreatDishForm>
                          </div>
                          <div class="tab-pane fade" id="profile-tab-pane" role="tabpanel" aria-labelledby="profile-tab" tabindex="1">
                           <CreatDishBom is_edit="props.is_edit" data="state.creatDishBom"  t-if="props.is_open and !state.isDishBomOneEditType"></CreatDishBom>    
                           <CreatDishBomOne is_edit="props.is_edit" data="state.creatDishBom"  t-if="props.is_open and state.isDishBomOneEditType"></CreatDishBomOne>
                           </div>
                           <div class="tab-pane fade" id="plat-tab-pane" role="tabpanel" aria-labelledby="plat-tab" tabindex="2">
                            <div class="mt-3 text-danger" t-if="!state.LoadSimilarDishBomDataName">请先输入菜品名称。</div>
                            <div class="mt-3" t-if="!state.LoadSimilarDishBomDataFlag and state.LoadSimilarDishBomDataName">加载中，请稍等...</div>
                            <CreatDishPlat data="state.CreatDishPlatData" t-if="state.LoadSimilarDishBomDataFlag and state.LoadSimilarDishBomDataName" ></CreatDishPlat>
                          </div>
                          <div class="tab-pane fade" id="similar-tab-pane" role="tabpanel" aria-labelledby="similar-tab" tabindex="3">
                            <div class="mt-3 text-danger" t-if="!state.LoadSimilarDishBomDataName">请先输入菜品名称。</div>
                            <div class="mt-3" t-if="!state.LoadSimilarDishBomDataFlag and state.LoadSimilarDishBomDataName">加载中，请稍等...</div>
                            <CreatDishSimilar data="state.CreatDishSimilarData" t-if="state.LoadSimilarDishBomDataFlag and state.LoadSimilarDishBomDataName"></CreatDishSimilar>
                          </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="text-danger" style="flex:1">
                            <t t-esc="state.msg"/>
                        </div>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" t-on-click.stop="handleSubmitModel" t-att-disabled="state.btnDisabled" t-if="!props.is_edit">
                            确定创建
                        </button>
                        <button type="button" class="btn btn-primary" t-on-click.stop="handleSubmitModel" t-att-disabled="state.btnDisabled" t-if="props.is_edit">
                            确定修改
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    static props = {
        is_open: {type: Boolean, optional: true},
        data: {type: Object, optional: true},
        is_edit: {type: Boolean, optional: true},
    };

    setup() {
        this.bus = new EventBus();
        useSubEnv({
            bus: this.bus
        })
        useChildSubEnv({// 只会在组件的子组件中挂载公共数据及方法
            setMsg:(msg)=>{
                this.state.msg = msg;
            },
            copyDishBom:(bom,type)=>{
                return this.copyDishBom(bom,type)
            },
        });
        this.state = useState({
            headerName:'',
            creatDishForm: {},
            creatDishBom:[],
            msg: '',
            btnDisabled: false,
            old_dish_key_name:'',
            CreatDishPlatData:[],
            CreatDishSimilarData:[],
            LoadSimilarDishBomDataFlag:false,
            LoadSimilarDishBomDataName:'',
            isDishBomOneEditType:false //菜品bom的编辑模式是否为1份，否则为100份
        });
        this.dish_key_id = '';

        onMounted(() => {
            let _this = this;
            this.creatDishModal = new bootstrap.Modal('#creatDishModal', {
                toggle: 'modal'
            });
            document.getElementById('creatDishModal').addEventListener('hidden.bs.modal', event => {
                _this.env.closeCreatDishModal();
                this.state.creatDishForm = {};
                this.state.creatDishBom = [];
                this.state.LoadSimilarDishBomDataFlag = false;
                this.state.LoadSimilarDishBomDataName = '';
                this.state.CreatDishPlatData = [];
                this.state.CreatDishSimilarData = [];
            });
            this.tab1 = new bootstrap.Tab('#home-tab');
            this.tab2 = new bootstrap.Tab('#profile-tab');
            this.tab3 = new bootstrap.Tab('#plat-tab');
            this.tab4 = new bootstrap.Tab('#similar-tab');


            document.getElementById('home-tab').addEventListener('shown.bs.tab', event => {
                // _this.state.msg = '';
            });
            document.getElementById('profile-tab').addEventListener('shown.bs.tab', event => {
                // _this.state.msg = '';
            });
            document.getElementById('plat-tab').addEventListener('shown.bs.tab', event => {
                _this.LoadSimilarDishBomData()
            });
            document.getElementById('similar-tab').addEventListener('shown.bs.tab', event => {
                _this.LoadSimilarDishBomData()
            });
        })

        onWillUpdateProps(nextProps => {
            // console.log(nextProps);
            if (nextProps.is_open) {
                return this.openModel(nextProps);
            }
        });


        this.handleSubmitModel = _.debounce(this.submitModel, 300);
    }
    copyDishBom(bom,type){
        // console.log('copyDishBom');
        // console.log(bom);
        this.bus.trigger('copyDishBom', {
            bom,type
        });
        this.tab2.show()
    }
    // 打开弹窗 赋值
    async openModel(props) {
        console.log('-------openModel---------');
        // console.log(JSON.parse(JSON.stringify(props.data)));
        // this.updata_index();
        this.state.isDishBomOneEditType = this.env.getIsDishBomOneEditType();
        this.state.btnDisabled = false;
        let newDish = JSON.parse(JSON.stringify(props.data));
        let dish_bom = [];
        let dish_key_id = '';
        if (props.is_edit) {
            newDish = this.env.getGlobal().dish_key[props.data.id];
            dish_key_id = newDish.id || '';
            this.state.old_dish_key_name = newDish.name;
            this.tab2.show();
            // this.tab3.show();
            if (props.data.dish_bom && props.data.dish_bom.length > 0) {
                props.data.dish_bom.forEach(v=>{
                    v.id = add_dish_bom_id();
                    dish_bom.push(v);
                });
            } else {
                dish_bom = this.env.getDishBomById(props.data.id);
            }
            dish_bom.forEach(v => {
                if (!v.net_material_id) {
                    v.net_material_id = this.env.getGlobal().material_item[v.material_id].net_material_id;
                }
                v.material_id_net_material_id = v.material_id + '_' + v.net_material_id;
            });
            this.state.headerName = '修改菜品：'+newDish.name;
        } else {
            newDish = JSON.parse(JSON.stringify(props.data));
            newDish.id = '';
            newDish.dish_cost = '';
            this.state.old_dish_key_name = '';
            dish_key_id = '';
            this.tab1.show();
            this.state.headerName = '创建菜品';
        }
        this.dish = newDish;
        this.dish_key_id = dish_key_id?formatId(dish_key_id):'';

        this.state.creatDishForm = {
            id:this.dish_key_id,
            cooking_method_id: newDish.cooking_method_id || 0,
            dish_cost: newDish.dish_cost || 0,
            price: newDish.price || 0,
            dish_top_category_id: newDish.dish_top_category_id || 0,
            easy_meal: newDish.easy_meal,
            name: newDish.name || '',
            shape_id: newDish.shape_id || 0,
        };
        this.state.creatDishBom = {
            dish_key_id:this.dish_key_id,
            dish_bom:dish_bom
        };

        if(newDish.name){
            // await
            setTimeout(() =>{
                this.LoadSimilarDishBomData(newDish.name,this.dish_key_id)
            }, 0);
        }
        this.state.msg = '';
        this.state.btnDisabled = false;
        this.creatDishModal.show();
    }

    async LoadSimilarDishBomData(dish_name,dish_key_id){
        if(!dish_name){
            let creatDishForm = {};
            this.bus.trigger('getForm', creatDishForm);
            dish_name = creatDishForm.name||'';
            dish_key_id = this.props.is_edit?this.dish_key_id:0;
        }else{
            dish_key_id = dish_key_id? dish_key_id:0;
        }
        let dish_top_category_id = this.dish.dish_top_category_id;

        if(this.state.LoadSimilarDishBomDataName == dish_name){
            return;
        }
        this.state.LoadSimilarDishBomDataName = dish_name;
        if(!dish_name){
            return;
        }
        this.state.LoadSimilarDishBomDataFlag = false;
        try {
            let {plat_bom_list,similar_dish_key_ids} = await this.env.LoadSimilarDishBomData(dish_top_category_id,dish_key_id,dish_name);
            this.state.CreatDishPlatData = plat_bom_list;
            this.state.CreatDishSimilarData = similar_dish_key_ids;
        }catch (e) {
            this.state.CreatDishPlatData = [];
            this.state.CreatDishSimilarData = [];
        }
        this.state.LoadSimilarDishBomDataFlag = true;
    }

    // 更新
    // updata_index() {
    //     let index = this.env.getIndex();
    //     this.index = index;
    //     // this.state.isGbom = this.index.user_settings.bom_qty_type == 'bom_qty';
    //     this.state.isGbom = this.env.getIsGbom();
    //
    //     this.dish_key = toObj(index.dish_key, 'id');
    //     this.material_item = toObj(index.material_item, 'id');
    //     this.net_material = toObj(index.net_material, 'id');
    //     this.dish_process_category = toObj(index.dish_process_category, 'id');
    //     this.material_purchase_unit_category = toObj(index.material_purchase_unit_category, 'id');
    //     let material_item_net_material = [];
    //     index.material_item.forEach(v => {
    //         material_item_net_material.push({
    //             id: v.id + '_' + v.net_material_id,
    //             name: this.net_material[v.net_material_id].name,
    //             material_name: v.name,
    //             material_id: v.id,
    //             net_material_id: v.net_material_id
    //         })
    //     });
    //     this.material_item_net_material = material_item_net_material;
    //     this.material_item_net_material_obj = toObj(material_item_net_material, 'id');
    // }
    // 提交
    async submitModel() {
        let checkObj = {
            msg:''
        };
        this.bus.trigger('checkForm', checkObj);
        this.bus.trigger('checkWhole', checkObj);
        this.state.msg = checkObj.msg;
        if (this.state.msg != '') {
            return false
        }
        let creatDishForm = {};
        this.bus.trigger('getForm', creatDishForm);
        let newData = {
            ...this.dish,
            ...creatDishForm
        };
        let getWhole = {};
        this.bus.trigger('getWhole', getWhole);
        newData.dish_bom_list = getWhole.list;
        if(!this.props.is_edit){
            newData.id = add_dish_key_id();
            newData.dish_bom_list.forEach(v => {
                v.dish_key_id = newData.id;
            });
        }
        if(newData.dish_bom_list.length>0){
            let dish_cost = 0;
            newData.dish_bom_list.forEach(v=>{
                let price = 0;
                let {gbom_qty_high,unit_id,material_id} = v;
                if(gbom_qty_high && unit_id && material_id){
                    price = this.env.getMaterialPrice(material_id,unit_id,gbom_qty_high);
                    price = price*0.01;
                    price = formatPrice(price);
                }
                dish_cost += price
            })
            newData.dish_cost = formatPrice(dish_cost);
        }else{
            newData.dish_cost = 0;
        }
        console.log('菜品提交...');
        console.log(newData);
        this.state.btnDisabled = true;
        let isChangedName = this.props.is_edit && (this.state.old_dish_key_name != newData.name);
        let res = await this.env.addDishAsync(newData, this.props.is_edit, isChangedName);
        console.log('---addDishAsync-res----');
        console.log(res);
        this.dish_key_id = res.id;
        if (typeof (this.props.data.callback) == 'function') {
            this.props.data.callback(res);
        }
        this.state.btnDisabled = false;
        this.creatDishModal.hide();

    }
}
CreatDishModal.components = {
    CreatDishForm,CreatDishBom,CreatDishPlat,CreatDishSimilar,CreatDishBomOne
}
export {
    CreatDishModal
}
